<?php

declare(strict_types=1);

namespace App\Command;

use App\Service\StatChannelService;
use App\Service\StatMchService;
use App\Utils\CustomUtils;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;

/**
 * @Command
 */
class StatChannelCommand extends HyperfCommand
{

    /**
     * 执行的命令行
     *
     * @var string
     */
    protected $name = 'statChannel:month';

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @Inject()
     * @var StatChannelService
     */
    private $StatChannelService;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        parent::__construct();
    }

    public function configure()
    {
        parent::configure();
        $this->setHelp('统计月份数据');
        $this->addOption('channelNos', 'd', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '统计通道');
        $this->addOption('statMonth', 'm', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '统计月份');
        $this->addOption('isForce', 'f', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '强制生成');
    }

    public function handle()
    {
        // 默认取上一个月
        $statMonth     = date('Y-m', strtotime("first day of last month"));
        $statStartTime = strtotime($statMonth."-01 00:00:00");
        $statEndTime   = strtotime("first day of next month", $statStartTime);
        $channelNos        = [];
        $isForce       = false;

        // 从 $input 获取 statMonth 参数
        $options = $this->input->getOptions();
        CustomUtils::xzxDebug($options);
        if (isset($options['statMonth']) && !empty($options['statMonth'])) {
            $statMonth     = $options['statMonth'][0];
            $statStartTime = strtotime($statMonth."-01 00:00:00");
            $statEndTime   = strtotime("first day of next month", $statStartTime);
        }
        if (isset($options['isForce']) && !empty($options['isForce'])) {
            $isForce       = !!$options['isForce'][0];
        }
        if (isset($options['channelNos']) && !empty($options['channelNos'])) {
            $channelNos = $options['channelNos'][0];
            $channelNos = explode(',', $channelNos);
        }

        $startTime = time();
        $this->line("统计开始，执行时间：" . date('Y-m-d H:i:s'), 'info');

        $this->StatChannelService->stat($statStartTime, $statEndTime, $statMonth, $channelNos, $isForce);

        $endTime = time();
        $this->line("统计结束，当前时间：" . date('Y-m-d H:i:s') . "，耗时：" . ($endTime - $startTime) . "s", 'info');
    }
}
